package leetcode101.tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Synhard
 * @version 1.0
 * @class Code23
 * @description 94. 二叉树的中序遍历
 * 给定一个二叉树的根节点 root ，返回它的 中序 遍历。
 *
 * 示例 1：
 *
 *
 * 输入：root = [1,null,2,3]
 * 输出：[1,3,2]
 * 示例 2：
 *
 * 输入：root = []
 * 输出：[]
 * 示例 3：
 *
 * 输入：root = [1]
 * 输出：[1]
 * 示例 4：
 *
 *
 * 输入：root = [1,2]
 * 输出：[2,1]
 * 示例 5：
 *
 *
 * 输入：root = [1,null,2]
 * 输出：[1,2]
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-06-27 9:02
 */
public class Code23 {
    public static void main(String[] args) {
        TreeNode head5 = new TreeNode(5);
        TreeNode head4 = new TreeNode(4);
        TreeNode head6 = new TreeNode(6);
        TreeNode head1 = new TreeNode(1);
        TreeNode head2 = new TreeNode(2);
        head4.left = head1;
        head4.right = head2;
        head5.left = head4;
        head5.right = head6;
        System.out.println(inorderTraversal(head5));
    }

    public List<Integer> inorderTraversal1(TreeNode root) { // 递归写法
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }

    private void dfs(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        dfs(root.left, res);
        res.add(root.val);
        dfs(root.right, res);
    }

    public static List<Integer> inorderTraversal(TreeNode root) { // 迭代写法
        if (root == null) {
            return new ArrayList<>();
        }
        Deque<TreeNode> stack = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        stack.addFirst(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peekFirst();
            if (cur != null) {
                stack.removeFirst();
                if (cur.right != null) {
                    stack.addFirst(cur.right);
                }
                stack.addFirst(cur);
                stack.addFirst(null);
                if (cur.left != null) {
                    stack.addFirst(cur.left);
                }
            } else {
                stack.removeFirst();
                res.add(stack.removeFirst().val);
            }
        }
        return res;
    }
}
